package com.wyx.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyx.DTO.DishDto;
import com.wyx.Dao.DishDao;
import com.wyx.Pojo.Dish;
import com.wyx.Pojo.DishFlavor;
import com.wyx.Service.DishService;
import com.wyx.Service.DishflavorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceimpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishDao dishDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishflavorService dishflavorService;

    /**
     * 新增菜品
     * @param dishDto
     */
    @Override
    @Transactional
    public void addnewdish(DishDto dishDto) {
        //向上转型了
        this.save(dishDto);

        Long id = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

        dishflavorService.saveBatch(flavors);
    }

    /**
     * 修改菜品的口味
     * @param dishDto
     */
    @Override
    @Transactional
    public void updatewithFlavor(DishDto dishDto) {
        //将dish表先修改了
        boolean b = this.updateById(dishDto);
        //然后再将dishflavor修改了
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        //先删除后新增 比较简单一点
        dishflavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            flavor.setId(null);
        }
        dishflavorService.saveBatch(flavors);
    }

    /**
     * 修改菜品的状态
     * @param ids
     */
    @Override
    public void updateStatus(String[] ids) {

        for (String id : ids) {
            Dish dish = dishDao.selectById(id);
            dish.setStatus(1);
            //删除缓存
            redisTemplate.delete("dish_"+dish.getCategoryId());
            dishDao.updateById(dish);
        }
    }
}
